package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter")
public class LoginCheckFilter implements Filter {
    private String[] authUrl = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**"
    };
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("[拦截请求:{}]",requestURI);
        boolean isAuth = checkAuthUrl(requestURI);
        if(isAuth){
           log.info("允许放行");
            filterChain.doFilter(request,response);
            return;
        }else if(request.getSession().getAttribute("employee") != null){
            log.info("[登录检查，已登录 id:{}]",request.getSession().getAttribute("employee"));
            Long id=(Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(id);
            filterChain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
    final AntPathMatcher pathMatcher = new AntPathMatcher();
    private boolean checkAuthUrl(String requestURI) {
        for (String URI : authUrl) {
            log.info("URI============="+URI);
            if(pathMatcher.match(URI,requestURI)){
                return true;
            }
        }
        return false;
    }
}
